package com.aniu.smslisten.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;

import androidx.annotation.Nullable;
import androidx.work.OutOfQuotaPolicy;

import com.aniu.smslisten.receiver.ServiceAlarmWorker;
import com.aniu.smslisten.receiver.SmsReceiver;
import com.aniu.smslisten.receiver.SystemBroadcastReceiver;
import com.aniu.smslisten.util.LogToFile;
import com.aniu.smslisten.util.NotificationUtil;
import com.aniu.smslisten.util.ServiceTimer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import static android.content.pm.ServiceInfo.FOREGROUND_SERVICE_TYPE_LOCATION;


public class SmsListenService extends Service {
    private static final int NOTIFICATION_ID = 1;
    private static final String TAG = "SmsListenService";
    private static final String PREFS_NAME = "SmsListenPrefs";
    private static final String KEY_SERVICE_RUNNING = "isServiceRunning";

    private static long NEXT_ALARM_TIME = 0L;
    private SystemBroadcastReceiver systemBroadcastReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        LogToFile.log(this, TAG, "SmsListenService onCreate called");
        startForeground(NOTIFICATION_ID, NotificationUtil.buildNotification(this, "Sms Listen Service", "Running in background", NOTIFICATION_ID), FOREGROUND_SERVICE_TYPE_LOCATION);
        scheduleWorkManagerAlarm(this);
        markServiceAsRunning(true);

        // 动态注册 SystemBroadcastReceiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        systemBroadcastReceiver = new SystemBroadcastReceiver();
        registerReceiver(systemBroadcastReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogToFile.log(this, TAG, "SmsListenService onStartCommand called");
        if (ServiceTimer.shouldNotRun()) {
            stopSelf();
            return START_NOT_STICKY;
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        LogToFile.log(this, TAG, "SmsListenService onDestroy called");
        stopForeground(true);
        showExitNotification();
        markServiceAsRunning(false);

        // 注销 SystemBroadcastReceiver
        if (systemBroadcastReceiver != null) {
            unregisterReceiver(systemBroadcastReceiver);
            systemBroadcastReceiver = null;
        }

        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void showExitNotification() {
        NotificationUtil.showNotification(this, "Sms Listen Service", "Service has stopped", NOTIFICATION_ID);
    }

    public static void scheduleWorkManagerAlarm(Context context) {
        // 使用WorkManager调度任务
        androidx.work.Data inputData = new androidx.work.Data.Builder()
                .putBoolean("isReschedule", true)
                .build();

        androidx.work.PeriodicWorkRequest workRequest = new androidx.work.PeriodicWorkRequest.Builder(ServiceAlarmWorker.class, 15, java.util.concurrent.TimeUnit.MINUTES)
                .setInputData(inputData)
                .build();

        androidx.work.WorkManager.getInstance(context).enqueueUniquePeriodicWork("SmsListenServiceAlarm", androidx.work.ExistingPeriodicWorkPolicy.REPLACE, workRequest);

        LogToFile.log(context, TAG, "Scheduling Periodic WorkManager alarm every 15 minutes");
    }


    // 新增方法：标记服务是否正在运行
    private void markServiceAsRunning(boolean isRunning) {
        SharedPreferences sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean(KEY_SERVICE_RUNNING, isRunning);
        editor.apply();
    }

    // 新增方法：查询服务是否正在运行
    public static boolean isServiceRunning(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        return sharedPreferences.getBoolean(KEY_SERVICE_RUNNING, false);
    }
}